package com.lkd.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dto.UserLoginDto;
import com.lkd.entity.Role;
import com.lkd.entity.User;
import com.lkd.exception.BusinessException;
import com.lkd.mapper.RoleMapper;
import com.lkd.mapper.UserMapper;
import com.lkd.properties.JwtProperties;
import com.lkd.service.RoleService;
import com.lkd.service.UserService;
import com.lkd.utils.JwtUtil;
import com.lkd.vo.LoginUserVo;
import com.lkd.vo.PageBean;
import com.lkd.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 聂德祥
 * @since 2024-08-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private JwtProperties jwtProperties;
@Autowired
private RoleMapper roleMapper;
    @Override
    public PageBean<UserVo> search(String userName, Integer pageIndex, Integer pageSize) {
        Page<UserVo> page = new Page(pageIndex, pageSize);
        page = getBaseMapper().search(page,userName);
        return new PageBean<>(page);
    }

    @Override
    public LoginUserVo login(UserLoginDto userLoginDto) {
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getLoginName, userLoginDto.getLoginName());
        User user = getBaseMapper().selectOne(eq);
        if(user==null){
            throw new BusinessException("用户不存在");
        }
        LambdaQueryWrapper<User> eq1 = new LambdaQueryWrapper<User>().eq(User::getPassword, userLoginDto.getPassword());
        if(!user.getPassword().equals(userLoginDto.getPassword())){
            throw new BusinessException("密码错误");
        }
        if(!user.getStatus()){
            throw new BusinessException("用户已被禁用");
        }
        user.getRoleId();
        Role role = roleMapper.selectById(user.getRoleId());
        System.out.println(role);
        LoginUserVo loginUserVo = BeanUtil.copyProperties(user, LoginUserVo.class);
        HashMap<String, Object> stringIntegerHashMap = new HashMap<>();
         stringIntegerHashMap.put("id", user.getId());
         stringIntegerHashMap.put("role", role.getRoleName());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecret(), jwtProperties.getAdminTtl(),stringIntegerHashMap );
        loginUserVo.setToken(token);
        return loginUserVo;
    }
}
